﻿using System.Globalization;
using System.Xml.Linq;
using IcicleFramework.Entities;
using Microsoft.Xna.Framework;

namespace IcicleFramework.Components.Movement
{
    public class BaseMovementComponent : BaseComponent, IMovementComponent
    {
        protected Vector2 velocity;

        public Vector2 Velocity
        {
            get { return velocity; }
            set
            {
                if (velocity != value)
                {
                    velocity = value;

                    if (OnVelocityChanged != null)
                        OnVelocityChanged(this);
                }
            }
        }

        public Vector2 MaxVelocity { get; set; }

        public event VelocityChangedHandler OnVelocityChanged;

        public BaseMovementComponent()
            :base()
        {
        }

        public BaseMovementComponent(IGameObject parent)
        {
            this.Parent = parent;
        }

        protected BaseMovementComponent(BaseMovementComponent old)
            :base(old)
        {
            this.Velocity = old.Velocity;
        }

        public override IBaseComponent DeepClone()
        {
            return new BaseMovementComponent(this);
        }

        public override void Update(GameTime gameTime)
        {
            float deltaT = (float) gameTime.ElapsedGameTime.TotalSeconds;

            Parent.Position = new Vector2(Parent.Position.X + this.Velocity.X * deltaT, Parent.Position.Y + this.Velocity.Y * deltaT);
        }

        public override void Deserialize(XElement element)
        {
            MaxVelocity = new Vector2(float.MaxValue);
            XElement maxVelElement = element.Element("maxVelocity");
            if (maxVelElement != null)
            {
                MaxVelocity = MaxVelocity.DeserializeOffset(maxVelElement);
            }
        }

        public override void Dispose()
        {
            OnVelocityChanged = null;

            base.Dispose();
        }

    }
}
